{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f84ae59b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import requests\n",
    "import time\n",
    "import datetime\n",
    "import os\n",
    "from IPython.display import clear_output # to clear screen while it print results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6226efce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# documentation https://docs.bitfinex.com/reference#rest-public-funding-stats\n",
    "# returns:\n",
    "\n",
    "# TIMESTAMP,\n",
    "# PLACEHOLDER,\n",
    "# PLACEHOLDER,\n",
    "# FRR,\n",
    "# AVG_PERIOD,\n",
    "# PLACEHOLDER,\n",
    "# PLACEHOLDER,\n",
    "# FUNDING_AMOUNT,\n",
    "# FUNDING_AMOUNT_USED\n",
    "# PLACEHOLDER,\n",
    "# PLACEHOLDER,\n",
    "# FUNDING_BELOW_THRESHOLD\n",
    "\n",
    "# # details\n",
    "# Fields\tType\tDescription\n",
    "# TIMESTAMP\tint\tTimestamp in milliseconds\n",
    "# FRR\tfloat\t1/365th of Flash Return Rate (To get the daily rate, use: rate x 365. To get the daily rate as percentage use: rate x 365 x 100. To get APR as percentage use rate x 100 x 365 x 365.)\n",
    "# AVG_PERIOD\tfloat\tAverage period for funding provided\n",
    "# FUNDING_AMOUNT\tfloat\tTotal funding provided\n",
    "# FUNDING_AMOUNT_USED\tfloat\tTotal funding provided that is used in positions\n",
    "# FUNDING_BELOW_THRESHOLD\tfloat\tSum of open funding offers <0.75%"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1501886",
   "metadata": {},
   "outputs": [],
   "source": [
    "BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), \"..\", \"..\"))\n",
    "OUTPUT_DIR = os.path.join(BASE_DIR, \"build\", \"output\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6dd6244",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "columnNames = ['TIMESTAMP', 'PLACEHOLDER', 'PLACEHOLDER', 'FRR', 'AVG_PERIOD', 'PLACEHOLDER', 'PLACEHOLDER', 'FUNDING_AMOUNT', 'FUNDING_AMOUNT_USED', 'PLACEHOLDER', 'PLACEHOLDER', 'FUNDING_BELOW_THRESHOLD', 'ticker']\n",
    "df_appended = pd.DataFrame()\n",
    "\n",
    "# note: UST is Tether not TerraUSD\n",
    "tickerList = ['UST']\n",
    "\n",
    "timeNow = int( time.time() )*1000\n",
    "\n",
    "# note: it will give data at hourly frequency, no more frequently\n",
    "for ticker in tickerList:\n",
    "    \n",
    "    #YMD HM\n",
    "    timeQuery = datetime.datetime(2013, 1, 1, 0, 0).timestamp()*1000 # Start date in milliseconds\n",
    "    \n",
    "    endQuery = timeNow\n",
    "\n",
    "    while True:\n",
    "\n",
    "        fundingQuery = 'https://api-pub.bitfinex.com/v2/funding/stats/f'+ str(ticker)+ \"/hist?limit=250&end=\" + str(endQuery)\n",
    "        print(fundingQuery)\n",
    "        \n",
    "        \n",
    "        try:\n",
    "            fundingRates = requests.get(fundingQuery).json()\n",
    "            if len(fundingRates) == 0:\n",
    "                break\n",
    "\n",
    "            fundingRates = pd.DataFrame(fundingRates)\n",
    "\n",
    "            fundingRates['ticker'] = ticker\n",
    "\n",
    "            fundingRates.columns= columnNames\n",
    "            fundingRates.columns= fundingRates.columns.str.lower()\n",
    "\n",
    "            fundingRates['timestamp_formatted'] = pd.to_datetime(fundingRates['timestamp'],unit='ms')\n",
    "            fundingRates = fundingRates.sort_values('timestamp', ascending=True)\n",
    "            print(fundingRates.head())\n",
    "\n",
    "            df_appended = df_appended.append(fundingRates, ignore_index=True)\n",
    "\n",
    "            endQuery = fundingRates['timestamp'].min()-1\n",
    "            clear_output(wait=True)\n",
    "            time.sleep(3)\n",
    "            \n",
    "        except: \n",
    "            time.sleep(100)\n",
    "            continue\n",
    "        \n",
    "    time.sleep(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7364775d",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_appended['annualized_apr'] = df_appended['frr']*100 * 365 * 365\n",
    "df_appended.loc[df_appended.ticker == \"UST\", 'ticker'] = \"USDT\" # Fix USDT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0dcdb0f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "filename = f'lending_rates_bitfinex.csv'\n",
    "df_appended.to_csv(os.path.join(OUTPUT_DIR,filename), index = False, header=True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "leverage_and_stablecoin_pegs",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
